<template>
  <div class="order-create-container">
    <div class="page-header">
      <div class="header-title">
        <h2>创建订单</h2>
        <span class="subtitle">创建新的运输订单</span>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">
          <el-icon><Back /></el-icon>返回列表
        </el-button>
      </div>
    </div>

    <el-card class="form-container">
      <el-steps :active="activeStep" finish-status="success" simple>
        <el-step title="基本信息" />
        <el-step title="货物信息" />
        <el-step title="费用信息" />
        <el-step title="确认提交" />
      </el-steps>

      <!-- 步骤1: 基本信息 -->
      <div v-if="activeStep === 0" class="step-content">
        <el-form
          ref="basicInfoForm"
          :model="orderForm"
          :rules="basicInfoRules"
          label-width="120px"
          class="order-form"
        >
          <el-form-item label="客户" prop="customerId">
            <el-select v-model="orderForm.customerId" placeholder="请选择客户" style="width: 100%">
              <el-option 
                v-for="customer in customerOptions" 
                :key="customer.value" 
                :label="customer.label" 
                :value="customer.value">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="订单类型" prop="orderType">
            <el-select v-model="orderForm.orderType" placeholder="请选择订单类型" style="width: 100%">
              <el-option label="普通运输" value="normal"></el-option>
              <el-option label="快速运输" value="express"></el-option>
              <el-option label="冷链运输" value="cold"></el-option>
              <el-option label="危险品运输" value="dangerous"></el-option>
            </el-select>
          </el-form-item>
          
          <el-divider content-position="left">起始地信息</el-divider>
          
          <el-form-item label="发货人" prop="sender">
            <el-input v-model="orderForm.sender" placeholder="请输入发货人姓名"></el-input>
          </el-form-item>
          
          <el-form-item label="发货人电话" prop="senderPhone">
            <el-input v-model="orderForm.senderPhone" placeholder="请输入发货人电话"></el-input>
          </el-form-item>
          
          <el-form-item label="起始地址" prop="fromAddress">
            <el-input v-model="orderForm.fromAddress" placeholder="请输入详细地址"></el-input>
          </el-form-item>
          
          <el-form-item label="预计提货时间" prop="expectedPickupTime">
            <el-date-picker
              v-model="orderForm.expectedPickupTime"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
          
          <el-divider content-position="left">目的地信息</el-divider>
          
          <el-form-item label="收货人" prop="receiver">
            <el-input v-model="orderForm.receiver" placeholder="请输入收货人姓名"></el-input>
          </el-form-item>
          
          <el-form-item label="收货人电话" prop="receiverPhone">
            <el-input v-model="orderForm.receiverPhone" placeholder="请输入收货人电话"></el-input>
          </el-form-item>
          
          <el-form-item label="目的地址" prop="toAddress">
            <el-input v-model="orderForm.toAddress" placeholder="请输入详细地址"></el-input>
          </el-form-item>
          
          <el-form-item label="预计送达时间" prop="expectedDeliveryTime">
            <el-date-picker
              v-model="orderForm.expectedDeliveryTime"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
          
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="orderForm.remarks"
              type="textarea"
              rows="3"
              placeholder="请输入备注信息"
            ></el-input>
          </el-form-item>
        </el-form>
        
        <div class="step-actions">
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>
      </div>

      <!-- 步骤2: 货物信息 -->
      <div v-if="activeStep === 1" class="step-content">
        <div class="goods-header">
          <h3>货物清单</h3>
          <el-button type="primary" size="small" @click="addGoodsItem">
            <el-icon><Plus /></el-icon>添加货物
          </el-button>
        </div>
        
        <el-table :data="orderForm.goods" border style="width: 100%">
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <el-table-column label="货物名称" min-width="150">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入货物名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="120">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity" :min="1" controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="重量(kg)" width="120">
            <template #default="scope">
              <el-input-number v-model="scope.row.weight" :min="0" :precision="2" controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="体积(m³)" width="120">
            <template #default="scope">
              <el-input-number v-model="scope.row.volume" :min="0" :precision="2" controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="包装方式" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.packageType" placeholder="请选择" style="width: 100%">
                <el-option label="纸箱" value="carton"></el-option>
                <el-option label="木箱" value="wooden"></el-option>
                <el-option label="托盘" value="pallet"></el-option>
                <el-option label="袋装" value="bag"></el-option>
                <el-option label="散装" value="bulk"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remarks" placeholder="请输入备注"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeGoodsItem(scope.$index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="goods-summary">
          <p>总数量: {{ totalQuantity }} 件</p>
          <p>总重量: {{ totalWeight.toFixed(2) }} kg</p>
          <p>总体积: {{ totalVolume.toFixed(2) }} m³</p>
        </div>
        
        <div class="step-actions">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>
      </div>

      <!-- 步骤3: 费用信息 -->
      <div v-if="activeStep === 2" class="step-content">
        <el-form
          ref="feeInfoForm"
          :model="orderForm"
          :rules="feeInfoRules"
          label-width="120px"
          class="order-form"
        >
          <el-form-item label="计费方式" prop="chargeType">
            <el-radio-group v-model="orderForm.chargeType">
              <el-radio label="weight">按重量计费</el-radio>
              <el-radio label="volume">按体积计费</el-radio>
              <el-radio label="distance">按距离计费</el-radio>
              <el-radio label="fixed">固定费用</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="基础运费" prop="basicFreight">
            <el-input-number
              v-model="orderForm.basicFreight"
              :min="0"
              :precision="2"
              :step="100"
              style="width: 200px"
            ></el-input-number>
            <span class="unit">元</span>
          </el-form-item>
          
          <el-form-item label="装卸费" prop="loadingFee">
            <el-input-number
              v-model="orderForm.loadingFee"
              :min="0"
              :precision="2"
              :step="50"
              style="width: 200px"
            ></el-input-number>
            <span class="unit">元</span>
          </el-form-item>
          
          <el-form-item label="保险费" prop="insuranceFee">
            <el-input-number
              v-model="orderForm.insuranceFee"
              :min="0"
              :precision="2"
              :step="50"
              style="width: 200px"
            ></el-input-number>
            <span class="unit">元</span>
          </el-form-item>
          
          <el-form-item label="其他费用" prop="otherFees">
            <el-input-number
              v-model="orderForm.otherFees"
              :min="0"
              :precision="2"
              :step="50"
              style="width: 200px"
            ></el-input-number>
            <span class="unit">元</span>
          </el-form-item>
          
          <el-form-item label="费用说明" prop="feeRemarks">
            <el-input
              v-model="orderForm.feeRemarks"
              type="textarea"
              rows="3"
              placeholder="请输入费用相关说明"
            ></el-input>
          </el-form-item>
          
          <el-divider></el-divider>
          
          <el-form-item label="订单总金额">
            <div class="total-amount">¥ {{ totalAmount.toFixed(2) }}</div>
          </el-form-item>
          
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="orderForm.paymentMethod" placeholder="请选择支付方式" style="width: 200px">
              <el-option label="预付款" value="prepaid"></el-option>
              <el-option label="到付" value="cod"></el-option>
              <el-option label="账期结算" value="credit"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        
        <div class="step-actions">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>
      </div>

      <!-- 步骤4: 确认提交 -->
      <div v-if="activeStep === 3" class="step-content">
        <div class="confirm-title">订单信息确认</div>
        
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="客户">{{ getCustomerName(orderForm.customerId) }}</el-descriptions-item>
          <el-descriptions-item label="订单类型">{{ getOrderTypeName(orderForm.orderType) }}</el-descriptions-item>
          <el-descriptions-item label="发货人">{{ orderForm.sender }}</el-descriptions-item>
          <el-descriptions-item label="发货人电话">{{ orderForm.senderPhone }}</el-descriptions-item>
          <el-descriptions-item label="起始地址">{{ orderForm.fromAddress }}</el-descriptions-item>
          <el-descriptions-item label="预计提货时间">{{ formatDateTime(orderForm.expectedPickupTime) }}</el-descriptions-item>
          <el-descriptions-item label="收货人">{{ orderForm.receiver }}</el-descriptions-item>
          <el-descriptions-item label="收货人电话">{{ orderForm.receiverPhone }}</el-descriptions-item>
          <el-descriptions-item label="目的地址">{{ orderForm.toAddress }}</el-descriptions-item>
          <el-descriptions-item label="预计送达时间">{{ formatDateTime(orderForm.expectedDeliveryTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ orderForm.remarks || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider></el-divider>
        
        <div class="confirm-title">货物信息</div>
        <el-table :data="orderForm.goods" border style="width: 100%">
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <el-table-column prop="name" label="货物名称" min-width="150"></el-table-column>
          <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
          <el-table-column prop="weight" label="重量(kg)" width="100"></el-table-column>
          <el-table-column prop="volume" label="体积(m³)" width="100"></el-table-column>
          <el-table-column prop="packageType" label="包装方式" width="120">
            <template #default="scope">
              {{ getPackageTypeName(scope.row.packageType) }}
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" min-width="150"></el-table-column>
        </el-table>
        
        <div class="goods-summary">
          <p>总数量: {{ totalQuantity }} 件</p>
          <p>总重量: {{ totalWeight.toFixed(2) }} kg</p>
          <p>总体积: {{ totalVolume.toFixed(2) }} m³</p>
        </div>
        
        <el-divider></el-divider>
        
        <div class="confirm-title">费用信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="计费方式">{{ getChargeTypeName(orderForm.chargeType) }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ getPaymentMethodName(orderForm.paymentMethod) }}</el-descriptions-item>
          <el-descriptions-item label="基础运费">¥ {{ orderForm.basicFreight.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="装卸费">¥ {{ orderForm.loadingFee.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="保险费">¥ {{ orderForm.insuranceFee.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="其他费用">¥ {{ orderForm.otherFees.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="费用说明" :span="2">{{ orderForm.feeRemarks || '无' }}</el-descriptions-item>
          <el-descriptions-item label="订单总金额" :span="2" class="total-row">
            <span class="total-amount">¥ {{ totalAmount.toFixed(2) }}</span>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="step-actions">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitting">提交订单</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Back } from '@element-plus/icons-vue'

const router = useRouter()

// 当前步骤
const activeStep = ref(0)

// 表单引用
const basicInfoForm = ref(null)
const feeInfoForm = ref(null)

// 提交状态
const submitting = ref(false)

// 客户选项
const customerOptions = [
  { value: 'customer1', label: '北京物流科技有限公司' },
  { value: 'customer2', label: '上海贸易有限公司' },
  { value: 'customer3', label: '广州电子科技有限公司' }
]

// 订单表单
const orderForm = reactive({
  customerId: '',
  orderType: 'normal',
  sender: '',
  senderPhone: '',
  fromAddress: '',
  expectedPickupTime: '',
  receiver: '',
  receiverPhone: '',
  toAddress: '',
  expectedDeliveryTime: '',
  remarks: '',
  goods: [
    { name: '', quantity: 1, weight: 0, volume: 0, packageType: 'carton', remarks: '' }
  ],
  chargeType: 'weight',
  basicFreight: 0,
  loadingFee: 0,
  insuranceFee: 0,
  otherFees: 0,
  feeRemarks: '',
  paymentMethod: 'prepaid'
})

// 基本信息验证规则
const basicInfoRules = {
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  orderType: [
    { required: true, message: '请选择订单类型', trigger: 'change' }
  ],
  sender: [
    { required: true, message: '请输入发货人姓名', trigger: 'blur' }
  ],
  senderPhone: [
    { required: true, message: '请输入发货人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  fromAddress: [
    { required: true, message: '请输入起始地址', trigger: 'blur' }
  ],
  expectedPickupTime: [
    { required: true, message: '请选择预计提货时间', trigger: 'change' }
  ],
  receiver: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入收货人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  toAddress: [
    { required: true, message: '请输入目的地址', trigger: 'blur' }
  ],
  expectedDeliveryTime: [
    { required: true, message: '请选择预计送达时间', trigger: 'change' }
  ]
}

// 费用信息验证规则
const feeInfoRules = {
  chargeType: [
    { required: true, message: '请选择计费方式', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

// 计算总数量
const totalQuantity = computed(() => {
  return orderForm.goods.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

// 计算总重量
const totalWeight = computed(() => {
  return orderForm.goods.reduce((sum, item) => sum + (item.weight || 0), 0)
})

// 计算总体积
const totalVolume = computed(() => {
  return orderForm.goods.reduce((sum, item) => sum + (item.volume || 0), 0)
})

// 计算订单总金额
const totalAmount = computed(() => {
  return (
    (orderForm.basicFreight || 0) +
    (orderForm.loadingFee || 0) +
    (orderForm.insuranceFee || 0) +
    (orderForm.otherFees || 0)
  )
})

// 获取客户名称
const getCustomerName = (id) => {
  const customer = customerOptions.find(item => item.value === id)
  return customer ? customer.label : ''
}

// 获取订单类型名称
const getOrderTypeName = (type) => {
  const typeMap = {
    'normal': '普通运输',
    'express': '快速运输',
    'cold': '冷链运输',
    'dangerous': '危险品运输'
  }
  return typeMap[type] || '未知'
}

// 获取包装方式名称
const getPackageTypeName = (type) => {
  const typeMap = {
    'carton': '纸箱',
    'wooden': '木箱',
    'pallet': '托盘',
    'bag': '袋装',
    'bulk': '散装'
  }
  return typeMap[type] || '未知'
}

// 获取计费方式名称
const getChargeTypeName = (type) => {
  const typeMap = {
    'weight': '按重量计费',
    'volume': '按体积计费',
    'distance': '按距离计费',
    'fixed': '固定费用'
  }
  return typeMap[type] || '未知'
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  const methodMap = {
    'prepaid': '预付款',
    'cod': '到付',
    'credit': '账期结算'
  }
  return methodMap[method] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 添加货物项
const addGoodsItem = () => {
  orderForm.goods.push({
    name: '',
    quantity: 1,
    weight: 0,
    volume: 0,
    packageType: 'carton',
    remarks: ''
  })
}

// 移除货物项
const removeGoodsItem = (index) => {
  if (orderForm.goods.length === 1) {
    ElMessage.warning('至少需要一项货物信息')
    return
  }
  
  orderForm.goods.splice(index, 1)
}

// 下一步
const nextStep = () => {
  if (activeStep.value === 0) {
    basicInfoForm.value.validate(valid => {
      if (valid) {
        activeStep.value++
      }
    })
  } else if (activeStep.value === 1) {
    // 验证货物信息
    if (orderForm.goods.some(item => !item.name)) {
      ElMessage.warning('请填写完整的货物名称')
      return
    }
    
    activeStep.value++
  } else if (activeStep.value === 2) {
    feeInfoForm.value.validate(valid => {
      if (valid) {
        activeStep.value++
      }
    })
  }
}

// 上一步
const prevStep = () => {
  activeStep.value--
}

// 返回列表
const goBack = () => {
  ElMessageBox.confirm(
    '确定要放弃当前编辑的订单吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    router.push('/order')
  }).catch(() => {})
}

// 提交订单
const submitOrder = () => {
  submitting.value = true
  
  // 模拟API调用
  setTimeout(() => {
    submitting.value = false
    
    ElMessage.success('订单提交成功')
    router.push('/order')
  }, 1500)
}

onMounted(() => {
  // 可以在这里初始化一些默认值
})
</script>

<style scoped>
.order-create-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.form-container {
  margin-bottom: 20px;
}

.el-steps {
  margin-bottom: 30px;
}

.step-content {
  padding: 20px 0;
}

.order-form {
  max-width: 800px;
}

.step-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.goods-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.goods-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.goods-summary {
  margin-top: 20px;
  text-align: right;
  font-size: 14px;
  color: #606266;
}

.unit {
  margin-left: 10px;
  color: #606266;
}

.total-amount {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.confirm-title {
  font-size: 18px;
  font-weight: bold;
  margin: 20px 0;
  color: #303133;
}

.total-row {
  background-color: #f8f8f8;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style>
